class NovelsController < ApplicationController
  before_filter :tags
  #new list show eidt
  def index
    @latest_novels = find_latest_novels
    @hotest_novels = [] || find_hotest_novels
  end
  
  #Read novel as a merged book
  def book
	#Place holder here
  end
  
  def open
    @novel = Novel.find params[:id]
    @novel.over=Novel::NOVEL_OVER+1 #other value means open
    begin
      @novel.save!
    rescue Exception=>detail
      flash[:message] = "文章因为某些原因未能开启!"
    end
    redirect_to :action=>"show", :id=>@novel
  end

  def over
    @novel = Novel.find params[:id]
    @novel.over=Novel::NOVEL_OVER
    begin
      @novel.save!
    rescue Exception=>detail
      flash[:message] = "文章因为某些原因未被结束!"
    end
    redirect_to :action=>"show", :id=>@novel
  end

  def list
    @novels = Novel.find :all, :order=>"updated_at DESC"
  end

  #List all merged fragment and assembled them to a article

  def read
    @novel = Novel.find params[:id]
    #TODO Should get all fragments by more appropriate sql search.
    merged = MergeHistory.find :all, :conditions=>["novel_id = ?", @novel.id], :order=>"fragment_number DESC"
    @fragments = []
    merged.each do |history|
      fragment = Fragment.find history.fragment_id
      (@fragments << fragment) if fragment
    end
    @fragments
  end

  def new
  end
  
  #TODO not work well now.
  def folk
	parent = Novel.find(params[:id])
	@novel = parent.children.create()
	@novel.user = User.find session[:user_id]
	@novel.folk_from_chapter = parent.current_chapter.id
	@novel.title = parent.title+"(folk)"
	@novel.parent = parent
	@novel.summary = "Please give summary..."
	render "edit"
  end
  
  def create
    if request.post?
      @novel = Novel.new params[:novel]
      @novel.user_id= session[:user_id]
      begin
		Novel.transaction do
		  @novel.save!
		  chapter = Chapter.new
	      chapter.novel = @novel
	      chapter.sequence = 1
		  chapter.save!
		end
        redirect_to novels_path(@novel)
      rescue Exception=>e
        @novel
      end
    else
      @novel = Novel.new
    end
  end

  def edit
    @novel = Novel.find params[:id]
    if request.post?
      begin
        @novel.update_attributes! params[:novel]
        @novel.save!
        redirect_to :action=>"show", :id=>@novel
      rescue Exception=>detail
        puts "Update novel failed. #{detail.message}"
      end
    end
    @novel
  end

  def show
    @novel = Novel.find params[:id]
	@chapter = @novel.chapters.last
    @fragments = @chapter.fragments
  end
  
  #Display the latest merged fragment to this novel
  def feed
	@novel = Novel.find params[:id]
    @fragments = Fragment.find :all, :order=>"updated_at DESC", :conditions=>["novel_id=?", @novel.id]
	respond_to do |format|
		format.xml  { render :xml => @fragments }  
		format.rss  { render :layout => false }  
	end
  end

  def pre_fragment
    #TODO Not finished this
    @current_fragment = find_fragment(params[:id], params[:fragment_number].to_i - 1)
    update_novel_fragment
  end

  def next_fragment
    @current_fragment = find_fragment(params[:id], params[:fragment_number].to_i + 1)
    update_novel_fragment
  end
  
  def tag_cloud
	  render :tags
  end

  private

  def tags
	@tags = Novel.tag_counts_on(:tags)
  end
  
  def current_fragment
    find_fragment @novel.id, @novel.fragment_number - 1
  end

  def find_fragment novel_id, fragment_number
    mh = MergeHistory.find :first, :conditions=>["fragment_number=? and novel_id=?", fragment_number, novel_id]
    return unless mh
    Fragment.find mh.fragment_id
  end

  def update_novel_fragment
    #return unless request.xhr?
    render :update do |page|
      page.replace_html 'novel_fragment', @current_fragment.content
      page.visual_effect :highlight, 'novel_fragment', :startcolor=>'#FFFF00', :duration=>'3'
    end
  end

  def find_latest_novels
    Novel.find :all, :limit=>5, :order=>"created_at DESC" || []
  end

  #The fragments has most fragments and merged fragments
  #TODO Here also need two many sql queries

  def find_hotest_novels
    # Novel.maximum :
    @hotest_novels = []
    hostest = Novel.find_by_sql "select n.id from novels as n inner join fragments as f on n.id=f.novel_id group by n.id order by count(*) desc limit 5;"
    hostest.each do |host|
      @hotest_novels << Novel.find(host.id)
    end
    @hotest_novels
  end

end
